<?php

namespace app\cps\service;

use app\model\Link;
use app\model\User;
use app\model\PayRecord;
use think\facade\Db;
use app\common\Common;
use app\common\Error;
use think\facade\Cache;
use app\model\DailyDeliveryData;
use app\model\Videos;
use app\model\ResponsibilityPerson;
use app\model\LaunchAccount;
use app\model\EchoRuleConfig;
use app\model\Subject;

class LaunchService
{
    private $model;
    private $userModel;
    private $payRecordModel;
    private $dailyDeliveryDataModel;
    private $videosModel;
    private $launchAccountModel;
    private $responsibilityPersonModel;
    private $echoRuleConfigModel;
    private $subjectModel;

    public function __construct(Link $model, User $userModel, PayRecord $payRecordModel, DailyDeliveryData $dailyDeliveryDataModel, Videos $videosModel, ResponsibilityPerson $responsibilityPersonModel, LaunchAccount $launchAccountModel, EchoRuleConfig $echoRuleConfigModel, Subject $subjectModel)
    {
        $this->model = $model;
        $this->userModel = $userModel;
        $this->payRecordModel = $payRecordModel;
        $this->dailyDeliveryDataModel = $dailyDeliveryDataModel;
        $this->videosModel = $videosModel;
        $this->responsibilityPersonModel = $responsibilityPersonModel;
        $this->launchAccountModel = $launchAccountModel;
        $this->echoRuleConfigModel = $echoRuleConfigModel;
        $this->subjectModel = $subjectModel;
    }

    // 获取投放总览统计数据
    public function getOverviewDataStatistics($userInfo)
    {
        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $where = ['responsibility_person_id' => $responsibilityPersonIds];
        } else {
            $where[] = ['official_account_id', '=', $userInfo['cps_used_official_account_id']];
            if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
                $where[] = ['responsibility_person_id', '=', $userInfo['cps_user_id']];
            }
        }

        $linkData = $this->model->getDataByWhere($where, 'id');
        $linkIds = array_column($linkData, 'id');

        // 累计充值/累计成本
        $deliveryData = $this->dailyDeliveryDataModel->getDataByWhere(['link_id' => $linkIds], 'total_recharge, cost, register_user_num, activation_user_num, actual_cost');
        $totalRecharge = array_sum(array_column($deliveryData, 'total_recharge'));
        $totalSpend = array_sum(array_column($deliveryData, 'actual_cost'));

        // 当月充值
        $startDate = date('Ym', time()) . '01';
        $endDate = date('Ymt', time());
        $thisMonthRecharge = $this->dailyDeliveryDataModel->where([['date', '>=', $startDate], ['date', '<=', $endDate], ['link_id', 'in', $linkIds]])->sum('total_recharge');

        // 上月充值
        $startDate = date('Ym', strtotime('-1 month')) . '01';
        $endDate = date('Ymt', strtotime(-date('d') . 'day'));
        $lastMonthRecharge = $this->dailyDeliveryDataModel->where([['date', '>=', $startDate], ['date', '<=', $endDate], ['link_id', 'in', $linkIds]])->sum('total_recharge');

        // 总关注用户
        $totalUser = array_sum(array_column($deliveryData, 'register_user_num'));

        $data = [
            'total_recharge' => round($totalRecharge, 2),
            'this_month_recharge' => round($thisMonthRecharge, 2),
            'last_month_recharge' => round($lastMonthRecharge, 2),
            'total_user' => $totalUser,
            'total_spend' => round($totalSpend, 2)
        ];

        return $data;
    }

    // 获取抖音今日实时在投数据
    public function getInvestingData($params, $userInfo)
    {
        ini_set('memory_limit', '-1');
        ini_set('max_execution_time', 0);

        $where[] = ['media_id', '=', 1];
        $totalClickNum = $totalNewUserCount = 0;

        if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $where[] = ['responsibility_person_id', '=', $userInfo['cps_user_id']];
        }
        // 链接id搜索
        if (!empty($params['link_id'])) {
            $where[] = ['id', '=', $params['link_id']];
        }
        // 短剧id搜索
        if (!empty($params['video_id'])) {
            $where[] = ['video_id', '=', $params['video_id']];
        }
        $linkWhere = [['link_switch', '=', 1], ['media_id', '=', 1]];

        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        $key1 = config('redis_key.real_time_investment_create_time') . date('Ymd');
        $key2 = config('redis_key.real_time_investment_link_user_register_num');

        // 取缓存数据
        if ($timeStamp = $redis->get($key1)) {

            $data = Db::name('real_time_data_cache')->where($where)->order('id', 'desc')->select()->toArray();
            $totalClickNum = 0;

            if ($data) {
                foreach ($data as $key => $item) {
                    // 获取点击数
                    // $redisKey = config('redis_key.link_same_day_click_num').date('Ymd').'-'.$item['id'];
                    // $clickNum = $redis->get($redisKey);
                    // $totalClickNum = $totalClickNum + $clickNum;

                    // 获取当日累计注册用户数
                    $linkRegisterUserNum = $redis->get($key2 . $item['id']);
                    $totalNewUserCount = $totalNewUserCount + $linkRegisterUserNum;
                }
                return [
                    'create_time' => date('Y-m-d H:i:s', $timeStamp),
                    'total_click_num' => $totalClickNum,
                    'total_new_user' => $totalNewUserCount,
                    'data' => $data
                ];
            } else {
                if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
                    $linkWhere[] = ['responsibility_person_id', '=', $userInfo['cps_user_id']];
                }
                $linkData = $this->model->getDataByWhere($linkWhere, 'id, video_id, video_detail_id, advertiser_id, responsibility_person_id');
                if (empty($linkData)) {
                    return [
                        'create_time' => date('Y-m-d H:i:s', $timeStamp),
                        'total_click_num' => $totalClickNum,
                        'total_new_user' => 0,
                        'data' => $data
                    ];
                }
            }
        }

        // 分销商链接不查询
        $distributorResponsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['pid' => Db::raw('IS NOT NULL')], 'id');
        $distributorResponsibilityPersonIds = array_column($distributorResponsibilityPerson, 'id');
        $linkWhere[] = ['responsibility_person_id', 'not in', $distributorResponsibilityPersonIds];
        $linkData = $this->model->getDataByWhere($linkWhere, 'id, video_id, video_detail_id, advertiser_id, responsibility_person_id, version, project_id, rebate, echo_rate, subject_id,link_type');

        $appId = config('tiktok.huge_amount.app_id');
        $secret = config('tiktok.huge_amount.secret');
        $accessToken = Common::getHugeAmountAccessToken($appId, $secret);

        $appId1 = config('tiktok.huge_amount_yaodao.app_id');
        $secret1 = config('tiktok.huge_amount_yaodao.secret');
        $accessToken1 = Common::getHugeAmountAccessToken($appId1, $secret1);

        $appId24 = config('tiktok.huge_amount_xingcan.app_id');
        $secret24 = config('tiktok.huge_amount_xingcan.secret');
        $accessToken24 = Common::getHugeAmountAccessToken($appId24, $secret24);

        // $appId5 = config('tiktok.huge_amount_sixseals_erfen.app_id');
        // $secret5 = config('tiktok.huge_amount_sixseals_erfen.secret');
        // $accessToken5 = Common::getHugeAmountAccessToken($appId5, $secret5);

        $hearder['json'] = 1;

        $startDate = date('Y-m-d');
        $endDate = date('Y-m-d');
        $data = $accountIds = $responsibilityPersonIds = [];
        // $url = 'https://ad.oceanengine.com/open_api/2/report/campaign/get/';
        $url = 'https://api.oceanengine.com/open_api/v3.0/project/list/';
        $url2 = 'https://api.oceanengine.com/open_api/v3.0/report/custom/get/';

        // 获取成本
        foreach ($linkData as $value) {
            if (empty($value['advertiser_id'])) {
                continue;
            }

            if ($value['subject_id'] == 8) {
                $hearder['headers'] = ['Access-Token:' . $accessToken1];
            } elseif ($value['subject_id'] == 24) {
                $hearder['headers'] = ['Access-Token:' . $accessToken24];
            }
            // elseif (in_array($value['subject_id'], config('tiktok.penshang'))) {
            //     $hearder['headers'] = ['Access-Token:' . $accessToken5];
            // }
            else {
                $hearder['headers'] = ['Access-Token:' . $accessToken];
            }

            $getProjectBody = [
                'advertiser_id' => intval($value['advertiser_id']),
                'fields' => ['project_id'],
                'page_size' => 100
            ];

            $getProjectRequestData = [];
            foreach ($getProjectBody as $k1 => $val1) {
                $getProjectRequestData[$k1] = is_string($val1) ? $val1 : json_encode($val1);
            }

            $getProjectResult = Common::_curl($url, $getProjectRequestData, 'GET', $hearder);
            $getProjectResult = json_decode($getProjectResult, true);

            if ($getProjectResult['code'] != 0) {
                return ['message' => $getProjectResult['message'] . '；link_id：' . $value['id']];
            }

            if (empty($getProjectResult['data']['list'])) {
                // $responsibilityPersonResult = $this->responsibilityPersonModel->getInfoById($value['responsibility_person_id'], 'name');
                // return ['message' => '链接ID：'.$value['id'].'（所属投放：'.$responsibilityPersonResult['name'].'） 没有在投放的项目，请关闭投放开关'];
                continue;
            }

            $string = '';
            foreach ($getProjectResult['data']['list'] as $val2) {
                $string .= $val2['project_id'] . ',';
            }
            $projectIdString = substr($string, 0, -1);
            $projectId = explode(',', $projectIdString);
            if (!empty($projectId)) $this->model->edit(['id' => $value['id'], 'project_id' => $projectIdString]);


            $body = [
                'dimensions'    => ['stat_time_day', 'cdp_project_name'],
                'advertiser_id' => $value['advertiser_id'], // 广告账户id
                'start_time'    => $startDate,
                'end_time'      => $endDate,
                'metrics'       => ['stat_cost'],
                'order_by'      => [
                    [
                        'field' => 'stat_time_day',
                        'type'  => 'DESC'
                    ]
                ],
                'filters'       => [
                    [
                        'field'    => 'cdp_project_id',
                        'type'     => 3,
                        'operator' => 1,
                        'values'   => $projectId // 项目id
                    ]
                ]
            ];

            $requestData = [];
            foreach ($body as $k => $val) {
                $requestData[$k] = is_string($val) ? $val : json_encode($val);
            }

            $result = Common::_curl($url2, $requestData, 'GET', $hearder);
            $result = json_decode($result, true);

            if (!$result['code']) {
                $value['cost'] = 0;
                // if (!empty($result['data']['rows'])) {
                //     foreach ($result['data']['rows'] as $key => $item) {
                //         $value['cost'] += $item['metrics']['stat_cost'];
                //     }
                // }
                if (!empty($result['data']['total_metrics'])) {
                    $value['cost'] = $result['data']['total_metrics']['stat_cost'];
                }

                $data[] = $value;
            } else {
                return ['message' => $result['message'] . '；link_id：' . $value['id']];
            }

            $accountIds[] = trim($value['advertiser_id']);
            $responsibilityPersonIds[] = $value['responsibility_person_id'];
        }

        $redisUserLinkRegisterData = [];
        if ($data) {
            // 短剧
            $videoIds = array_column($data, 'video_id');
            $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
            $videos = array_column($videoData, 'name', 'id');

            $ids = array_column($data, 'id');
            $userWhere = [
                ['link_id', 'in', $ids],
                ['activation_time', 'between', [date('Y-m-d') . ' 00:00:00', date('Y-m-d') . ' 23:59:59']]
            ];
            $userInfo = $this->userModel->getBatchDataByWhere($userWhere, 'id, link_id');
            $payData = $this->payRecordModel->getInfo(['link_id' => $ids, 'status' => 1, 'consume_date' => date('Ymd')], 'link_id, uid, total_fee, activation_time');

            $newUids = $newUserPayData = $rechargeNumber = $payResult = $userData = [];

            if ($userInfo) {

                foreach ($userInfo as $key => $value) {
                    $newUids[] = $value['id'];
                    $redisUserLinkRegisterData[$value['link_id']][] = $value['id'];
                }

                // 当天这个链接上的用户数据
                $links = array_column($userInfo, 'link_id');
                $linkUser = array_count_values($links); // 统计相同link_id 的个数
            }

            $newUserNum = [];
            // 当天新用户充值（当期充值）
            $startTime = strtotime(date('Y-m-d'));
            $endTime = strtotime(date('Y-m-d')) + 86400;
            foreach ($payData as $key => $value) {
                if (strtotime($value['activation_time']) >= $startTime && $endTime > strtotime($value['activation_time'])) {
                    $newUserPayData[$value['link_id']][] = $value['total_fee'];
                    $newUserNum[$value['link_id']][] = $value['uid'];
                }
                // $payResult[$value['link_id']][] = $value['total_fee'];
                $rechargeNumber[$value['link_id']][] = $value['uid'];
            }

            // 获取返点数据
            $launchAccountData = $this->launchAccountModel->getDataByWhere(['account_id' => $accountIds], 'account_id, rebate');
            $launchAccount = array_column($launchAccountData, 'rebate', 'account_id');

            // 获取负责人数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'id, name');
            $responsibilityPerson = array_column($responsibilityPersonData, 'name', 'id');

            foreach ($data as $key => $item) {
                $data[$key]['video_name'] = $videos[$item['video_id']];

                $currentRecharge = empty($newUserPayData[$item['id']]) ? 0 : array_sum($newUserPayData[$item['id']]);
                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值

                // by huangxiaoshan 2023-07-13 当期充值95折扣
                $tmp_recharge_discount = round(bcmul((string)$currentRecharge, '0.95', 3), 2); // 当期95充值;

                $data[$key]['current_recharge_discount'] = $tmp_recharge_discount;
                // end.

                $data[$key]['current_recovery'] = $item['cost'] == 0 ? 0 : round($currentRecharge / $item['cost'] * 100, 2) . '%'; // 当期回收
                $conversionNumber = empty($rechargeNumber[$item['id']]) ? 0 : count(array_unique($rechargeNumber[$item['id']])); // 充值人数
                $data[$key]['conversion_number'] = $conversionNumber;

                $newRechargeNumber = empty($newUserPayData[$item['id']]) ? 0 : count($newUserPayData[$item['id']]); // 新充笔数
                $newUserNumber = empty($newUserNum[$item['id']]) ? 0 : count(array_unique($newUserNum[$item['id']])); // 新充人数
                $data[$key]['new_recharge_number'] = $newRechargeNumber;
                $data[$key]['new_user_number'] = $newUserNumber;
                $data[$key]['conversion_cost'] = $newUserNumber == 0 ? 0 : round($item['cost'] / $newUserNumber, 2); // 转化成本

                // 转化率
                $data[$key]['conversion_rate'] = !empty($linkUser[$item['id']]) ? round($newUserNumber / $linkUser[$item['id']] * 100, 2) . '%' : '0%';
                $totalClickNum += empty($userData[$item['id']]) ? 0 : $userData[$item['id']];

                $data[$key]['fans_cost'] = !empty($linkUser[$item['id']]) ? round($item['cost'] / $linkUser[$item['id']], 2) : 0; // 粉丝成本
                // $totalRecharge = empty($payResult[$item['id']]) ? 0 : array_sum($payResult[$item['id']]); // 当天累计充值
                $data[$key]['total_recharge'] = $currentRecharge;

                $data[$key]['per_capita_contribution'] = $newUserNumber == 0 ? 0 : round($currentRecharge / $newUserNumber, 2); // 人均贡献

                $userLinkRegisterNum = empty($redisUserLinkRegisterData[$item['id']]) ? 0 : count($redisUserLinkRegisterData[$item['id']]);
                $redis->set($key2 . $item['id'], $userLinkRegisterNum, 15 * 60);
                $data[$key]['media_id'] = 1; // 抖音

                // 实际花费
                $actualCost = 0;
                if (!empty($item['rebate'])) {
                    $actualCost = round($item['cost'] / ($item['rebate'] / 100 + 1), 2);
                } elseif (!empty($launchAccount[$item['advertiser_id']])) {
                    $actualCost = round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2);
                }
                unset($data[$key]['rebate']);
                // $actualCost = !empty($launchAccount[$item['advertiser_id']]) ? round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2) : 0;
                $data[$key]['actual_recovery'] = $actualCost == 0 ? 0 : round($currentRecharge / $actualCost * 100, 2) . '%'; // 实际回收
                $data[$key]['actual_cost'] = $tmp_actual_cost = round($actualCost, 2);

                // by huangxiaoshan 2023-07-13 当期充值95折扣后净利润.
                $data[$key]['current_recharge_profit'] = bcsub((string)$tmp_recharge_discount, (string)$tmp_actual_cost, 2);
                // end

                // 负责人数据
                $data[$key]['responsibility_person_name'] = $responsibilityPerson[$item['responsibility_person_id']];

                $data[$key]['revenue'] = round($currentRecharge - $actualCost, 2); // 营收情况
                unset($data[$key]['subject_id']);
            }
        }

        Db::name('real_time_data_cache')->where(['media_id' => 1])->delete(true);
        $bool = Db::name('real_time_data_cache')->insertAll($data);
        if ($bool) {
            $redis->set($key1, time(), 15 * 60); // 数据产生的时间
        }

        $data = Db::name('real_time_data_cache')->where($where)->order('id', 'desc')->select()->toArray();
        foreach ($data as $item) {

            // 获取点击数
            $redisKey = config('redis_key.link_same_day_click_num') . date('Ymd') . '-' . $item['id'];
            $clickNum = $redis->get($redisKey);
            $totalClickNum = $totalClickNum + $clickNum;

            // 获取当日累计注册用户数
            $linkRegisterUserNum = $redis->get($key2 . $item['id']);
            $totalNewUserCount = $totalNewUserCount + $linkRegisterUserNum;
        }

        $result = [
            'create_time' => date('Y-m-d H:i:s'),
            'total_click_num' => $totalClickNum,
            'total_new_user' => $totalNewUserCount,
            'data' => $data
        ];

        return $result;
    }

    // 获取抖音今日实时在投数据
    public function getTiktokInvestingData($params, $userInfo)
    {
        ini_set('memory_limit', '-1');
        ini_set('max_execution_time', 0);

        $where[] = ['media_id', '=', 1];
        $where[] = ['link_switch', '=', 1];
        $totalClickNum = $totalNewUserCount = 0;

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        } elseif ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $where[] = ['responsibility_person_id', '=', $userInfo['cps_user_id']];
        }
        // 链接id搜索
        if (!empty($params['link_id'])) {
            $where[] = ['id', '=', $params['link_id']];
        }
        // 账户id搜索
        if (!empty($params['advertiser_id'])) {
            $where[] = ['advertiser_id', '=', $params['advertiser_id']];
        }
        // 短剧id搜索
        if (!empty($params['video_id'])) {
            $where[] = ['video_id', '=', $params['video_id']];
        }

        // 链接类型搜索
        if (!empty($params['link_type'])) {
            $where[] = ['link_type', '=', $params['link_type']];
        }
        // 负责人搜索
        if (!empty($params['responsibility_person_id'])) {
            $where[] = ['responsibility_person_id', '=', $params['responsibility_person_id']];
        }
    
        // 分销商链接不查询
        $distributorResponsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['is_distributor' => 1], 'id');
        $distributorResponsibilityPersonPids = array_column($distributorResponsibilityPerson, 'id');

        $distributorPitcher = $this->responsibilityPersonModel->getDataByWhere(['pid' => $distributorResponsibilityPersonPids], 'id');
        $distributorResponsibilityPersonIds = array_column($distributorPitcher, 'id');

        $where[] = ['responsibility_person_id', 'not in', $distributorResponsibilityPersonIds];
        $linkData = $this->model->getDataByWhere($where, 'id, video_id, video_detail_id, advertiser_id, responsibility_person_id, version, project_id, rebate, echo_rate, subject_id, created_at, is_new_back_setting, echo_rule_config_id,link_type');

        // 获取redis花费数据
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        // 获取redis花费数据
        
        $redisCostData1 = $redis->get('oceanengine_business_ad_data_today:18006505024'); // 杭州泉起抖小
        $redisCostData2 = $redis->get('oceanengine_business_ad_data_today:sybyn6'); // 杭州泉起
        $redisCostData3 = $redis->get('oceanengine_business_ad_data_today:sybyn1'); // 泉起-抖小-艺达

        $redisCostDataLiuYi = json_decode($redisCostData1, true);
        $redisCostDataGuangZhou = json_decode($redisCostData2, true);
        $redisCostDataTree = json_decode($redisCostData3, true);
        $redisCostData = [];
        if (!empty($redisCostDataLiuYi['data'])) {
            $redisCostData = $redisCostData + $redisCostDataLiuYi['data'];
        }
        if (!empty($redisCostDataGuangZhou['data'])) {
            $redisCostData = $redisCostData + $redisCostDataGuangZhou['data'];
        }
        if (!empty($redisCostDataTree['data'])) {
            $redisCostData = $redisCostData + $redisCostDataTree['data'];
        }
        if (empty($redisCostData)) {
            $redisCostData = $redis->get(config('redis_key.tiktok_real_time_cost') . date('Ymd'));
            $redisCostData = json_decode($redisCostData, true);
            $syncTimeLiuYi = $syncTimeGuangZhou = date('Y-m-d H:i:s');
        } else {
            $syncTimeLiuYi = $redisCostDataLiuYi['sync_time'];
            $syncTimeGuangZhou = $redisCostDataGuangZhou['sync_time'];
        }

        // 获取成本
        $data = $newBackLinkIds = [];
        // $queryDate = [];
        // for ($i = 1; $i < 4; $i++) {
        //     $queryDate[] = date('Ymd', time() - $i * 86400);
        // }
        // $startDate = date('Y-m-d');
        // $createTime = strtotime($startDate) - 3 * 86400;
        // $linkIds = [];
        foreach ($linkData as $value) {
            if (empty($value['advertiser_id'])) {
                continue;
            }

            // 花费
            $value['cost'] = !empty($redisCostData[$value['advertiser_id']]['stat_cost']) ? $redisCostData[$value['advertiser_id']]['stat_cost'] : 0;
            // 账户余额
            $value['balance'] = !empty($redisCostData[$value['advertiser_id']]['advertiser_balance']) ? $redisCostData[$value['advertiser_id']]['advertiser_balance'] : 0;
            $data[] = $value;

            $responsibilityPersonIds[] = $value['responsibility_person_id'];

            // if (empty(intval($value['cost'])) && $value['created_at'] < $createTime) {
            //     $historyCost = Db::name('daily_delivery_data')->where(['date' => $queryDate, 'link_id' => $value['id']])->sum('cost');
            //     if (empty(ceil($historyCost))) {
            //         $linkIds[] = $value['id'];
            //     }
            // }

            if ($value['is_new_back_setting'] == 2) {
                $newBackLinkIds[] = $value['echo_rule_config_id'];
                $newBackLink[$value['id']] = $value['echo_rule_config_id'];
            }
        }

        // 关闭已停止投放的链接
        // if (!empty($linkIds)) {
        //     Db::name('link')->where(['id' => $linkIds])->update(['link_switch' => 0]);
        // }

        $redisUserLinkRegisterData = [];
        if ($data) {
            // 短剧
            $videoIds = array_column($data, 'video_id');
            $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
            $videos = array_column($videoData, 'name', 'id');

            $ids = array_column($data, 'id');
            $userWhere = [
                ['link_id', 'in', $ids],
                ['activation_time', 'between', [date('Y-m-d') . ' 00:00:00', date('Y-m-d') . ' 23:59:59']]
            ];
            $userInfo = $this->userModel->getBatchDataByWhere($userWhere, 'id, link_id');
            $payData = $this->payRecordModel->getInfo(['link_id' => $ids, 'status' => 1, 'consume_date' => date('Ymd')], 'link_id, uid, total_fee, activation_time, pay_merchant');

            $newUids = $newUserPayData = $rechargeNumber = $payResult = $userData = [];

            if ($userInfo) {

                foreach ($userInfo as $key => $value) {
                    $newUids[] = $value['id'];
                    $totalNewUserCount = count($newUids);
                    $redisUserLinkRegisterData[$value['link_id']][] = $value['id'];
                }

                // 当天这个链接上的用户数据
                $links = array_column($userInfo, 'link_id');
                $linkUser = array_count_values($links); // 统计相同link_id 的个数
            }

            $newUserNum = $tencentPayData = [];

            // 当天新用户充值（当期充值）
            $startTime = strtotime(date('Y-m-d'));
            $endTime = strtotime(date('Y-m-d')) + 86400;
            foreach ($payData as $key => $value) {
                if (strtotime($value['activation_time']) >= $startTime && $endTime > strtotime($value['activation_time'])) {
                    $newUserPayData[$value['link_id']][] = $value['total_fee'];
                    $newUserNum[$value['link_id']][] = $value['uid'];
                    if ($value['pay_merchant'] == 15) {
                        $tencentPayData[$value['link_id']][] = $value['total_fee'];
                    }
                }
                // $payResult[$value['link_id']][] = $value['total_fee'];
                $rechargeNumber[$value['link_id']][] = $value['uid'];
            }

            // 获取负责人数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'id, name');
            $responsibilityPerson = array_column($responsibilityPersonData, 'name', 'id');

            // 获取新回传数据
            if ($newBackLinkIds) {
                $newBackData = $this->echoRuleConfigModel->getDataByWhere(['id' => $newBackLinkIds], 'id, back_rate_type, echo_rate, pass, leak');
                $newBack = array_column($newBackData, NULL, 'id');
            }

            foreach ($data as $key => $item) {
                $data[$key]['video_name'] = $videos[$item['video_id']];

                $currentRecharge = empty($newUserPayData[$item['id']]) ? 0 : array_sum($newUserPayData[$item['id']]);
                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值

                // by huangxiaoshan 2023-07-13 当期充值95折扣
                $tencentTenPercent = empty($tencentPayData[$item['id']]) ? 0 : array_sum($tencentPayData[$item['id']]);
                $currentRechargeDiscount = round($currentRecharge * 0.9, 2); // 当期95充值;

                $data[$key]['current_recharge_discount'] = $currentRechargeDiscount;
                // end.

                $data[$key]['current_recovery'] = $item['cost'] == 0 ? 0 : round($currentRechargeDiscount / $item['cost'] * 100, 2) . '%'; // 当期回收
                $conversionNumber = empty($rechargeNumber[$item['id']]) ? 0 : count(array_unique($rechargeNumber[$item['id']])); // 充值人数
                $data[$key]['conversion_number'] = $conversionNumber;

                $newRechargeNumber = empty($newUserPayData[$item['id']]) ? 0 : count($newUserPayData[$item['id']]); // 新充笔数
                $newUserNumber = empty($newUserNum[$item['id']]) ? 0 : count(array_unique($newUserNum[$item['id']])); // 新充人数
                $data[$key]['new_recharge_number'] = $newRechargeNumber;
                $data[$key]['new_user_number'] = $newUserNumber;
                // $data[$key]['conversion_cost'] = $newUserNumber == 0 ? 0 : round($item['cost'] / $newUserNumber, 2); // 转化成本

                // 转化率
                $data[$key]['conversion_rate'] = !empty($linkUser[$item['id']]) ? round($newUserNumber / $linkUser[$item['id']] * 100, 2) . '%' : '0%';
                $totalClickNum += empty($linkUser[$item['id']]) ? 0 : $linkUser[$item['id']];

                // $data[$key]['fans_cost'] = !empty($linkUser[$item['id']]) ? round($item['cost'] / $linkUser[$item['id']], 2) : 0; // 粉丝成本
                // $totalRecharge = empty($payResult[$item['id']]) ? 0 : array_sum($payResult[$item['id']]); // 当天累计充值
                $data[$key]['total_recharge'] = $currentRecharge;

                $data[$key]['per_capita_contribution'] = $newUserNumber == 0 ? 0 : round($currentRecharge / $newUserNumber, 2); // 人均贡献

                $userLinkRegisterNum = empty($redisUserLinkRegisterData[$item['id']]) ? 0 : count($redisUserLinkRegisterData[$item['id']]);
                // $redis->set($key2.$item['id'], $userLinkRegisterNum, 15*60);
                $data[$key]['media_id'] = 1; // 抖音

                // 实际花费
                $actualCost = round($item['cost'] / ($item['rebate'] / 100 + 1), 2);

                unset($data[$key]['rebate']);

                $data[$key]['conversion_cost'] = $newUserNumber == 0 ? 0 : round($actualCost / $newUserNumber, 2); // 转化成本
                $data[$key]['fans_cost'] = !empty($userData[$item['id']]) ? round($actualCost / $userData[$item['id']], 2) : 0; // 粉丝成本

                // $actualCost = !empty($launchAccount[$item['advertiser_id']]) ? round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2) : 0;
                $data[$key]['actual_recovery'] = $actualCost == 0 ? 0 : round($currentRechargeDiscount / $actualCost * 100, 2) . '%'; // 实际回收
                $data[$key]['actual_cost'] = round($actualCost, 2);

                // by huangxiaoshan 2023-07-13 当期充值95折扣后净利润.
                $data[$key]['current_recharge_profit'] = round($currentRechargeDiscount - $actualCost, 2);
                // end

                // 负责人数据
                $data[$key]['responsibility_person_name'] = $responsibilityPerson[$item['responsibility_person_id']];

                $data[$key]['revenue'] = round($currentRecharge - $actualCost, 2); // 营收情况
                // by huangxiaoshan 2023-07-24 人均订单数.
                $data[$key]['avg_person_order'] = 0;
                if($newRechargeNumber && $newUserNumber) {
                    $data[$key]['avg_person_order'] = round(bcdiv((string)$newRechargeNumber, (string)$newUserNumber, 3), 2);
                }
                // end
                unset($data[$key]['subject_id']);

                // 获取新回传规则的回传率
                if ($item['is_new_back_setting'] == 2) {
                    $newBackInfo = !empty($newBack[$newBackLink[$item['id']]]) ? $newBack[$newBackLink[$item['id']]] : [];
                    if ($newBackInfo) {
                        if ($newBackInfo['back_rate_type'] == 0) {
                            $data[$key]['echo_rate'] = $newBackInfo['echo_rate'];
                        } else {
                            $data[$key]['echo_rate'] = $newBackInfo['pass'] .':'. $newBackInfo['leak'];
                        }
                    }
                }
            }
        }

        $result = [
            'create_time' => date('Y-m-d H:i:s'),
            'total_click_num' => $totalClickNum,
            'total_new_user' => $totalNewUserCount,
            'data' => $data,
            'sync_time' => $syncTimeLiuYi,
            'sync_time_guang_zhou' => $syncTimeGuangZhou
        ];

        return $result;
    }

    // 获取快手今日实时在投数据
    public function getKuaiInvestingData($params, $userInfo)
    {
        $where[] = ['media_id', '=', 2];
        $totalClickNum = $totalNewUserCount = 0;

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        } elseif ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $where[] = ['responsibility_person_id', '=', $userInfo['cps_user_id']];
        }
        // 链接id搜索
        if (!empty($params['link_id'])) {
            $where[] = ['id', '=', $params['link_id']];
        }
        // 短剧id搜索
        if (!empty($params['video_id'])) {
            $where[] = ['video_id', '=', $params['video_id']];
        }
        $linkWhere = ['link_switch' => 1, 'media_id' => 2];

        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        $key1 = config('redis_key.kwai_real_time_investment_create_time') . date('Ymd');
        $key2 = config('redis_key.kwai_real_time_investment_link_user_register_num');

        // 取缓存数据
        if ($timeStamp = $redis->get($key1)) {
            $timeStamp = $redis->get($key1);
            $data = Db::name('real_time_data_cache')->where($where)->order('id', 'desc')->select()->toArray();
            $totalClickNum = 0;
            if ($data) {
                // $total_order_count = $this->linkOrderCount($data);
                foreach ($data as $key => $item) {
                    // 获取点击数
                    $redisKey = config('redis_key.link_same_day_click_num') . date('Ymd') . '-' . $item['id'];
                    $clickNum = $redis->get($redisKey);
                    $totalClickNum = $totalClickNum + $clickNum;

                    // 获取当日累计注册用户数
                    $linkRegisterUserNum = $redis->get($key2 . $item['id']);
                    $totalNewUserCount = $totalNewUserCount + $linkRegisterUserNum;
                }
                return [
                    'create_time' => date('Y-m-d H:i:s', $timeStamp),
                    'total_click_num' => $totalClickNum,
                    'total_new_user' => $totalNewUserCount,
                    // 'total_order_count'=>$total_order_count,
                    'data' => $data
                ];
            } else {
                if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
                    $linkWhere['responsibility_person_id'] = $userInfo['cps_user_id'];
                }
                $linkData = $this->model->getDataByWhere($linkWhere, 'id, video_id, video_detail_id, advertiser_id, responsibility_person_id');
                if (empty($linkData)) {
                    return [
                        'create_time' => date('Y-m-d H:i:s', $timeStamp),
                        'total_click_num' => $totalClickNum,
                        'total_new_user' => 0,
                        // 'total_order_count'=>0,
                        'data' => $data
                    ];
                } else { // by huangxiaoshan update 2023-07-13
                    return [
                        'create_time' => date('Y-m-d H:i:s', $timeStamp),
                        'total_click_num' => $totalClickNum,
                        'total_new_user' => 0,
                        // 'total_order_count'=>0,
                        'data' => []
                    ];
                }
            }
        }

        $linkData = $this->model->getDataByWhere($linkWhere, 'id, video_id, video_detail_id, advertiser_id, responsibility_person_id, rebate, echo_rate,link_type');

        $appId = config('kwai.magnetic_force.app_id');
        $secret = config('kwai.magnetic_force.secret');
        $accessToken = Common::getKwaiAccessToken($appId, $secret);

        $hearder['headers'] = ['Access-Token: ' . $accessToken];
        $hearder['json'] = 1;

        $startDate = date('Y-m-d');
        $endDate = date('Y-m-d');
        $data = $accountIds = $responsibilityPersonIds = [];
        $url = 'https://ad.e.kuaishou.com/rest/openapi/v1/advertiser/fund/daily_flows';

        //
        foreach ($linkData as $value) {
            if (empty($value['advertiser_id'])) {
                continue;
            }

            // 获取成本
            $requestData = [
                'advertiser_id' => intval($value['advertiser_id']),
                'start_date' => $startDate,
                'end_date' => $endDate,
            ];

            $result = Common::_curl($url, $requestData, 'POST', $hearder);
            $result = json_decode($result, true);

            if (!$result['code']) {
                $value['cost'] = empty($result['data']['details'][0]) ? 0 : $result['data']['details'][0]['daily_charge']; // 今日花费
                $data[] = $value;
            } else {
                return ['message' => $result['message']];
            }

            $accountIds[] = $value['advertiser_id'];
            $responsibilityPersonIds[] = $value['responsibility_person_id'];
        }

        $redisUserLinkRegisterData = [];
        if ($data) {
            // 短剧
            $videoIds = array_column($data, 'video_id');
            $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
            $videos = array_column($videoData, 'name', 'id');

            $ids = array_column($data, 'id');
            $userWhere = [
                ['link_id', 'in', $ids],
                ['activation_time', 'between', [date('Y-m-d') . ' 00:00:00', date('Y-m-d') . ' 23:59:59']]
            ];
            $userInfo = $this->userModel->getBatchDataByWhere($userWhere, 'id, link_id');
            $payData = $this->payRecordModel->getInfo(['link_id' => $ids, 'status' => 1, 'consume_date' => date('Ymd')], 'link_id, uid, total_fee, activation_time, pay_merchant');

            $newUids = $newUserPayData = $rechargeNumber = $payResult = $userData = [];

            if ($userInfo) {

                foreach ($userInfo as $key => $value) {
                    $newUids[] = $value['id'];
                    $redisUserLinkRegisterData[$value['link_id']][] = $value['id'];
                }

                // 当天这个链接上的用户数据
                $links = array_column($userInfo, 'link_id');
                $userData = array_count_values($links);
                // $userData = array_column($userInfo, NULL, 'link_id');
            }

            $newUserNum = $tencentPayData = [];
            // 当天新用户充值（当期充值）
            $startTime = strtotime(date('Y-m-d'));
            $endTime = strtotime(date('Y-m-d')) + 86400;

            foreach ($payData as $key => $value) {
                if (strtotime($value['activation_time']) >= $startTime && $endTime > strtotime($value['activation_time'])) {
                    $newUserPayData[$value['link_id']][] = $value['total_fee'];
                    $newUserNum[$value['link_id']][] = $value['uid'];
                    if ($value['pay_merchant'] == 15) {
                        $tencentPayData[$value['link_id']][] = $value['total_fee'];
                    }
                }
                $payResult[$value['link_id']][] = $value['total_fee'];
                $rechargeNumber[$value['link_id']][] = $value['uid'];
            }

            // 获取返点数据
            $launchAccountData = $this->launchAccountModel->getDataByWhere(['account_id' => $accountIds], 'account_id, rebate');
            $launchAccount = array_column($launchAccountData, 'rebate', 'account_id');

            // 获取负责人数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'id, name');
            $responsibilityPerson = array_column($responsibilityPersonData, 'name', 'id');

            foreach ($data as $key => $item) {
                $data[$key]['video_name'] = $videos[$item['video_id']];

                $currentRecharge = empty($newUserPayData[$item['id']]) ? 0 : array_sum($newUserPayData[$item['id']]);
                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值

                // by huangxiaoshan 2023-07-13 当期充值95折扣
                // $tmp_recharge_discount = round(bcmul((string)$currentRecharge,'0.95',3), 2); // 当期95充值;
                $virtualPayment = empty($tencentPayData[$item['id']]) ? 0 : array_sum($tencentPayData[$item['id']]);
                $currentRechargeDiscount = round($currentRecharge * 0.9, 2);
                $data[$key]['current_recharge_discount'] = $currentRechargeDiscount;
                // end.

                $data[$key]['current_recovery'] = $item['cost'] == 0 ? 0 : round($currentRecharge / $item['cost'] * 100, 2) . '%'; // 当期回收
                $conversionNumber = empty($rechargeNumber[$item['id']]) ? 0 : count(array_unique($rechargeNumber[$item['id']])); // 充值人数
                $data[$key]['conversion_number'] = $conversionNumber;

                $newRechargeNumber = empty($newUserPayData[$item['id']]) ? 0 : count($newUserPayData[$item['id']]); // 新充笔数
                $newUserNumber = empty($newUserNum[$item['id']]) ? 0 : count(array_unique($newUserNum[$item['id']])); // 新充人数
                $data[$key]['new_recharge_number'] = $newRechargeNumber;
                $data[$key]['new_user_number'] = $newUserNumber;
                $data[$key]['conversion_cost'] = $newUserNumber == 0 ? 0 : round($item['cost'] / $newUserNumber, 2); // 转化成本

                // 转化率
                $redisKey = config('redis_key.link_same_day_click_num') . date('Ymd') . '-' . $item['id'];
                $clickNum = $redis->get($redisKey);
                if (empty($clickNum) || empty($newUserNum[$item['id']])) {
                    $data[$key]['conversion_rate'] = '0%';
                } else {
                    $data[$key]['conversion_rate'] = round($newUserNumber / $clickNum * 100, 2) . '%';
                }

                $data[$key]['fans_cost'] = !empty($userData[$item['id']]) ? round($item['cost'] / $userData[$item['id']]) : 0; // 粉丝成本
                // $totalRecharge = empty($payResult[$item['id']]) ? 0 : array_sum($payResult[$item['id']]); // 当天累计充值
                $data[$key]['total_recharge'] = $currentRecharge;

                $data[$key]['per_capita_contribution'] = $newUserNumber == 0 ? 0 : round($currentRecharge / $newUserNumber, 2); // 人均贡献

                $userLinkRegisterNum = empty($redisUserLinkRegisterData[$item['id']]) ? 0 : count($redisUserLinkRegisterData[$item['id']]);
                $redis->set($key2 . $item['id'], $userLinkRegisterNum, 15 * 60);
                $data[$key]['media_id'] = 2; // 抖音

                // 实际花费
                $actualCost = 0;
                if (!empty($item['rebate'])) {
                    $actualCost = round($item['cost'] / ($item['rebate'] / 100 + 1), 2);
                } elseif (!empty($launchAccount[$item['advertiser_id']])) {
                    $actualCost = round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2);
                }
                unset($data[$key]['rebate']);
                // $actualCost = !empty($launchAccount[$item['advertiser_id']]) ? round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2) : 0;
                $data[$key]['actual_recovery'] = $actualCost == 0 ? 0 : round($currentRecharge / $actualCost * 100, 2) . '%'; // 实际回收
                $data[$key]['actual_cost'] = round($actualCost, 2);

                // by huangxiaoshan 2023-07-13 当期充值95折扣后净利润.
                $data[$key]['current_recharge_profit'] = round($currentRechargeDiscount - $actualCost, 2);
                // end

                // 负责人数据
                $data[$key]['responsibility_person_name'] = $responsibilityPerson[$item['responsibility_person_id']];

                $data[$key]['revenue'] = round($currentRecharge - $actualCost, 2); // 营收情况
            }
        }

        Db::name('real_time_data_cache')->where(['media_id' => 2])->delete(true);
        $bool = Db::name('real_time_data_cache')->insertAll($data);
        if ($bool) {
            $redis->set($key1, time(), 15 * 60); // 数据产生的时间
        }

        $data = Db::name('real_time_data_cache')->where($where)->order('id', 'desc')->select()->toArray();
        foreach ($data as $item) {

            // 获取点击数
            $redisKey = config('redis_key.link_same_day_click_num') . date('Ymd') . '-' . $item['id'];
            $clickNum = $redis->get($redisKey);
            $totalClickNum = $totalClickNum + $clickNum;

            // 获取当日累计注册用户数
            $linkRegisterUserNum = $redis->get($key2 . $item['id']);
            $totalNewUserCount = $totalNewUserCount + $linkRegisterUserNum;
        }

        $result = [
            'create_time' => date('Y-m-d H:i:s'),
            'total_click_num' => $totalClickNum,
            'total_new_user' => $totalNewUserCount,
            'data' => $data
        ];

        return $result;
    }

    // 获取投放数据列表
    public function getLaunchDataList($params, $userInfo)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];
        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        } elseif ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $where[] = ['official_account_id', '=', $userInfo['cps_used_official_account_id']];
            $where[] = ['responsibility_person_id', '=', $userInfo['cps_user_id']];
        } else {
            $where[] = [
                'official_account_id', '=', $userInfo['cps_used_official_account_id']
            ];
        }

        $linkData = $this->model->getDataByWhere($where, 'id');
        $linkIds = array_column($linkData, 'id');

        //
        $offset = ($page - 1) * $limit;

        $where = [];
        $where[] = ['link_id', 'in', $linkIds];
        if (!empty($params['start_date'])) {
            $where[] = ['date', '>=', date('Ymd', strtotime($params['start_date']))];
        }
        if (!empty($params['end_date'])) {
            $where[] = ['date', '<=', date('Ymd', strtotime($params['end_date']))];
        }
        if(!empty($params['date_time'])){
            $date_time = explode('~', $params['date_time']);
            $where[] = ['date','>=',date('Ymd', strtotime($date_time[0]))];
            $where[] = ['date','<=',date('Ymd', strtotime($date_time[1]))];
        }
        if (!empty($params['platform'])) {
            $where[] = ['platform', '=', $params['platform']];
        }

        if (empty($params['platform'])) {
            $total = Db::name('daily_delivery_data')->where($where)->group('date, platform')->count();
            $data = Db::name('daily_delivery_data')->field('date')->where($where)->group('date, platform')->order('id desc')->limit($offset, $limit)->select()->toArray();
        } else {
            $total = Db::name('daily_delivery_data')->where($where)->group('date')->count();
            $data = Db::name('daily_delivery_data')->field('date')->where($where)->group('date')->order('id desc')->limit($offset, $limit)->select()->toArray();
        }

        if ($total == 0) {
            return ['total' => 0, 'total_page' => 0, 'data' => []];
        }

        $totalPage = ceil($total / $limit);

        $date = array_column($data, 'date');
        $where = [];
        $where[] = ['link_id', 'in', $linkIds];
        $where[] = ['date', 'in', $date];
        if (!empty($params['platform'])) {
            $where[] = ['platform', '=', $params['platform']];
        }

        $result = Db::name('daily_delivery_data')->where($where)->order('date desc, platform asc')->select()->toArray();

        $totalData = [];
        foreach ($result as $key => $dailyDate) {
            $totalData[$dailyDate['date'] . '_' . $dailyDate['platform']][] = $dailyDate;
        }

        $returnData = [];
        foreach ($totalData as $key => $value) {

            list($date, $platform) = explode('_', $key);

            $totalCost = empty($value) ? 0 : round(array_sum(array_column($value, 'cost')), 2); // 当天花费
            $actualCost = empty($value) ? 0 : round(array_sum(array_column($value, 'actual_cost')), 2); // 实际花费
            $activationUserNum = empty($value) ? 0 : array_sum(array_column($value, 'activation_user_num')); // 激活用户数
            $registerUserNum = empty($value) ? 0 : array_sum(array_column($value, 'register_user_num')); // 注册用户数
            if ($date >= 20230821) {
                $currentRecharge = empty($value) ? 0 : round(array_sum(array_column($value, 'current_recharge')) * 0.9, 2); // 当期充值
                $totalIncome = empty($value) ? 0 : round(array_sum(array_column($value, 'total_recharge')) * 0.9, 2); // 累计充值
            } else {
                $currentRecharge = empty($value) ? 0 : round(array_sum(array_column($value, 'current_recharge')) * 0.95, 2); // 当期充值
                $totalIncome = empty($value) ? 0 : round(array_sum(array_column($value, 'total_recharge')) * 0.95, 2); // 累计充值
            }
            $totalRecharge = empty($value) ? 0 : round(array_sum(array_column($value, 'total_recharge')), 2); // 累计充值
            $virtualPayment = empty($value['virtual_payment']) ? 0 : $value['virtual_payment'];
            $currentRechargeDiscount = round($currentRecharge * 0.9, 2);
            $currentRecovery = empty($totalCost) ? '0%' : round($currentRechargeDiscount / $totalCost, 4) * 100 . '%'; // 返前ROI
            $actualRecovery = empty($actualCost) ? '0%' : round($currentRechargeDiscount / $actualCost, 4) * 100 . '%'; // 返后ROI
            $totalRecovery = empty($actualCost) ? 0 : round($totalIncome / $actualCost, 4) * 100 . '%'; // 累计回收
            $fansCost = !empty($activationUserNum) ? round($totalCost / $activationUserNum, 2) : 0; // 粉丝成本
            $revenue = round($totalIncome - $actualCost, 2); // 营收情况
            $rechargeNumber = empty($value) ? 0 : array_sum(array_column($value, 'recharge_number')); // 订单数
            $conversionNumber = empty($value) ? 0 : array_sum(array_column($value, 'conversion_number')); // 充值人数
            $newRechargeNumber = empty($value) ? 0 : array_sum(array_column($value, 'new_recharge_number')); // 新充笔数
            $newUserNumber = empty($value) ? 0 : array_sum(array_column($value, 'new_user_number')); // 新充人数
            $conversionCost = empty($newUserNumber) ? 0 : round($totalCost / $newUserNumber, 2); // 转化成本
            $perCapitaContribution = empty($conversionNumber) ? 0 : round($totalRecharge / $conversionNumber, 2); // 人均贡献
            $conversionRate = empty($activationUserNum) ? '0%' : round($newUserNumber / $activationUserNum * 100, 2) . '%'; // 转化率 = 新充人数 / 激活用户数

            $item = [
                'platform' => $platform,
                'date' => substr($date, 0, 4) . '-' . substr($date, 4, 2) . '-' . substr($date, 6, 2),
                'total_cost' => $totalCost,
                'actual_cost' => $actualCost,
                'activation_user_num' => $activationUserNum,
                'register_user_num' => $registerUserNum,
                'current_recharge' => $currentRecharge,
                'current_recharge_discount' => $currentRechargeDiscount, // by xiaoshan update
                'current_recharge_profit' => round($totalIncome - $actualCost, 2), // by xiaoshan update
                'current_recovery' => $currentRecovery,
                'actual_recovery' => $actualRecovery,
                'total_recharge' => $totalRecharge,
                'total_income' => $totalIncome,
                'total_recovery' => $totalRecovery,
                'fans_cost' => $fansCost,
                'revenue' => $revenue,
                'recharge_number' => $rechargeNumber,
                'conversion_number' => $conversionNumber,
                'new_recharge_number' => $newRechargeNumber,
                'new_user_number' => $newUserNumber,
                'conversion_cost' => $conversionCost,
                'per_capita_contribution' => $perCapitaContribution,
                'conversion_rate' => $conversionRate
            ];

            $returnData[] = $item;
        }

        return ['total' => $total, 'total_page' => $totalPage, 'data' => $returnData];
    }

    // 获取投放数据详情
    public function getLaunchDataDetail($params, $userInfo)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $date = str_replace('-', '', $params['date']);

        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        if (!empty($params['media_id']) && $params['media_id'] == 1) {
            $redisKey = config('redis_key.huge_amount_advertising_account_info');
        } elseif (!empty($params['media_id']) && $params['media_id'] == 2) {
            $redisKey = config('kwai.magnetic_force_advertising_account_info');
        } elseif (!empty($params['media_id']) && $params['media_id'] == 3) {
            $redisKey = config('baidu.baidu_sub_user_list');
            $advertiserData = $redis->hGetAll($redisKey);
        }

        $where = [];
        $where[] = ['media_id', '=', $params['media_id']];
        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        } elseif ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $where[] = ['official_account_id', '=', $userInfo['cps_used_official_account_id']];
            $where[] = ['responsibility_person_id', '=', $userInfo['cps_user_id']];
        } else {
            $where[] = [
                'official_account_id', '=', $userInfo['cps_used_official_account_id']
            ];
        }
        // 负责人搜索
        if (!empty($params['responsibility_person_id'])) {
        $where[] = ['responsibility_person_id', '=', $params['responsibility_person_id']];
        }
        $linkData = $this->model->getDataByWhere($where, 'id');
        $linkIds = array_column($linkData, 'id');
        $where = [];
        $where[] = ['link_id', 'in', $linkIds];

        // 短剧id
        if (!empty($params['video_id'])) {
            $linkData = $this->model->getDataByWhere(['video_id' => $params['video_id']], 'id');
            $where[] = ['link_id', 'in', array_column($linkData, 'id')];
        }

        // 链接id
        if (!empty($params['link_id'])) {
            $where[] = ['link_id', '=', $params['link_id']];
        }

        // 1=微信小程序 2=抖音小程序 3=h5 4=app
        if (!empty($params['link_type'])) {
            $where[] = ['link_type', '=', $params['link_type']];
        }

        // 搜索指定日期
        if (!empty($params['start_date'])) {
            $where[] = ['date', '>=', date('Ymd', strtotime($params['start_date']))];
        }
        if (!empty($params['end_date'])) {
            $where[] = ['date', '<=', date('Ymd', strtotime($params['end_date']))];
        }

        if (empty($params['start_date']) && empty($params['end_date'])) {
            $where[] = ['date', '=', $date];
        }

        $offset = ($page - 1) * $limit;
        $total = Db::name('daily_delivery_data')->where($where)->count();
        $totalPage = ceil($total / $limit);

        if ($total == 0) {
            return ['total' => 0, 'total_page' => 0, 'data' => []];
        }

        $fields = 'date, platform, link_id, advertiser_id, cost, current_recharge, current_recovery, conversion_number, conversion_cost, new_recharge_number, new_user_number, conversion_rate, fans_cost, total_recharge, revenue, per_capita_contribution, register_user_num, actual_cost, activation_user_num';

        if (!empty($params['cost_sort'])) {
            $order = 'cost ' . $params['cost_sort'];
        } elseif (!empty($params['actual_cost_sort'])) {
            $order = 'actual_cost ' . $params['actual_cost_sort'];
        } else {
            $order = 'id desc';
        }

        $data = Db::name('daily_delivery_data')->field($fields)->where($where)->order($order)->limit($offset, $limit)->select()->toArray();

        $linkIds = array_column($data, 'link_id');
        $linkData = $this->model->getDataByWhere(['id' => $linkIds], 'id, video_id');
        $videoIds = array_column($linkData, 'video_id');
        $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
        $video = [];
        foreach ($videoData as $key => $value) {
            foreach ($linkData as $k => $item) {
                if ($item['video_id'] == $value['id']) {
                    $video[$item['id']] = $value['name'];
                }
            }
        }

        $linkData = $this->model->getDataByWhere(['id' => $linkIds], 'id, responsibility_person_id');
        $responsibilityPersonIds = array_column($linkData, 'responsibility_person_id');
        $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'id, name');
        $responsibilityPerson = array_column($responsibilityPersonData, 'name', 'id');

        foreach ($linkData as $key => $value) {
            $linkData[$key]['responsibility_person_name'] = $responsibilityPerson[$value['responsibility_person_id']];
        }
        $linkAndResponsibilityPersonData = array_column($linkData, 'responsibility_person_name', 'id');

        if ($params['media_id'] == 1 || $params['media_id'] == 2) {
            // 抖音和快手
            $length = $redis->scard($redisKey);
            $redisData = $advertiserData = [];

            if ($length) {
                $result = $redis->smembers($redisKey);
                foreach ($result as $item) {
                    $redisData[] = json_decode($item, true);
                }
                $advertiserData = array_column($redisData, 'advertiser_name', 'advertiser_id'); // advertiser_id,advertiser_name
            }
        }

        foreach ($data as $key => $value) {
            $data[$key]['date'] = substr($value['date'], 0, 4) . '-' . substr($value['date'], 4, 2) . '-' . substr($value['date'], 6, 2);
            $data[$key]['video_name'] = empty($video[$value['link_id']]) ? '' : $video[$value['link_id']];
            $data[$key]['advertiser_name'] = empty($advertiserData[$value['advertiser_id']]) ? '' : $advertiserData[$value['advertiser_id']];

            if ($value['date'] >= 20230821) {
                $data[$key]['current_income'] = round($value['current_recharge'] * 0.9, 2);
                $data[$key]['total_income'] = round($value['total_recharge'] * 0.9, 2);
            } else {
                $data[$key]['current_income'] = round($value['current_recharge'] * 0.95, 2);
                $data[$key]['total_income'] = round($value['total_recharge'] * 0.95, 2);
            }
            $data[$key]['current_recovery'] = !empty($value['actual_cost']) && $value['actual_cost'] != '0.00' ? round($data[$key]['current_income'] / $value['actual_cost'] * 100, 2) . '%' : '0%';
            $data[$key]['total_recovery'] = !empty($value['actual_cost']) && $value['actual_cost'] != '0.00' ? round($data[$key]['total_income'] / $value['actual_cost'] * 100, 2) . '%' : '0%';

            $data[$key]['revenue'] = round($data[$key]['total_income'] - $value['actual_cost'], 2);
            $data[$key]['responsibility_person_name'] = $linkAndResponsibilityPersonData[$value['link_id']];
        }

        return ['total' => $total, 'total_page' => $totalPage, 'data' => $data];
    }

    // 获取投放总览查看统计数据
    public function getLaunchDataDetailCount($params, $userInfo)
    {
        $date = str_replace('-', '', $params['date']);

        $where = [];
        $where[] = ['media_id', '=', $params['media_id']];
        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        } elseif ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $where[] = ['official_account_id', '=', $userInfo['cps_used_official_account_id']];
            $where[] = ['responsibility_person_id', '=', $userInfo['cps_user_id']];
        } else {
            $where[] = [
                'official_account_id', '=', $userInfo['cps_used_official_account_id']
            ];
        }
        // 负责人搜索
        if (!empty($params['responsibility_person_id'])) {
        $where[] = ['responsibility_person_id', '=', $params['responsibility_person_id']];
        }
        $linkData = $this->model->getDataByWhere($where, 'id');
        $linkIds = array_column($linkData, 'id');

        $where = [];
        $where[] = ['link_id', 'in', $linkIds];

        // 短剧id
        if (!empty($params['video_id'])) {
            $linkData = $this->model->getDataByWhere(['video_id' => $params['video_id']], 'id');
            $where[] = ['link_id', 'in', array_column($linkData, 'id')];
        }

        // 链接id
        if (!empty($params['link_id'])) {
            $where[] = ['link_id', '=', $params['link_id']];
        }

        // 1=微信小程序 2=抖音小程序 3=h5 4=app
        if (!empty($params['link_type'])) {
            $where[] = ['link_type', '=', $params['link_type']];
        }

        // 搜索指定日期
        if (!empty($params['start_date'])) {
            $where[] = ['date', '>=', date('Ymd', strtotime($params['start_date']))];
        }
        if (!empty($params['end_date'])) {
            $where[] = ['date', '<=', date('Ymd', strtotime($params['end_date']))];
        }

        if (empty($params['start_date']) && empty($params['end_date'])) {
            $where[] = ['date', '=', $date];
        }

        $data = Db::name('daily_delivery_data')->field('sum(cost) as cost, sum(actual_cost) as actual_cost, sum(register_user_num) as register_user_num, sum(activation_user_num) as activation_user_num, sum(current_recharge) as current_recharge, sum(total_recharge) as total_recharge, sum(conversion_number) as conversion_number, sum(new_recharge_number) as new_recharge_number, sum(new_user_number) as new_user_number, sum(revenue) as revenue, sum(case when date < 20230821 then current_recharge * 0.95 else current_recharge * 0.9 end) as current_income, sum(case when date < 20230821 then total_recharge * 0.95 else total_recharge * 0.9 end) as total_income')->where($where)->find();

        $data['revenue'] = round($data['total_income'] - $data['actual_cost'], 2);
        $data['current_recovery'] = !empty($data['actual_cost']) ? round($data['current_income'] / $data['actual_cost'] * 100, 2) . '%' : '0%';
        $data['total_recovery'] = !empty($data['actual_cost']) ? round($data['total_income'] / $data['actual_cost'] * 100, 2) . '%' : '0%';

        $data['total_income'] = round($data['total_income'], 2);
        $data['current_income'] = round($data['current_income'], 2);
        return $data;
    }

    // 获取百度今日实时在投数据
    public function getBaiduInvestingData($params, $userInfo)
    {
        $where[] = ['media_id', '=', 3];
        $totalClickNum = $totalNewUserCount = 0;

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        } elseif ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $where[] = ['responsibility_person_id', '=', $userInfo['cps_user_id']];
        }
        // 链接id搜索
        if (!empty($params['link_id'])) {
            $where[] = ['id', '=', $params['link_id']];
        }
        // 短剧id搜索
        if (!empty($params['video_id'])) {
            $where[] = ['video_id', '=', $params['video_id']];
        }
        $linkWhere = ['link_switch' => 1, 'media_id' => 3];

        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        $key1 = config('redis_key.baidu_real_time_investment_create_time') . date('Ymd');
        $key2 = config('redis_key.baidu_real_time_investment_link_user_register_num');

        // 取缓存数据
        if ($timeStamp = $redis->get($key1)) {
            // if(true) {
            $timeStamp = $redis->get($key1);
            $data = Db::name('real_time_data_cache')->where($where)->order('id', 'desc')->select()->toArray();
            $totalClickNum = 0;
            if ($data) {
                // $total_order_count = $this->linkOrderCount($data);
                foreach ($data as $key => $item) {
                    // 获取点击数
                    $redisKey = config('redis_key.link_same_day_click_num') . date('Ymd') . '-' . $item['id'];
                    $clickNum = $redis->get($redisKey);
                    $totalClickNum = $totalClickNum + $clickNum;

                    // 获取当日累计注册用户数
                    $linkRegisterUserNum = $redis->get($key2 . $item['id']);
                    $totalNewUserCount = $totalNewUserCount + $linkRegisterUserNum;
                }
                return [
                    'create_time' => date('Y-m-d H:i:s', $timeStamp),
                    'total_click_num' => $totalClickNum,
                    'total_new_user' => $totalNewUserCount,
                    // 'total_order_count'=>$total_order_count,
                    'data' => $data
                ];
            } else {
                if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
                    $linkWhere['responsibility_person_id'] = $userInfo['cps_user_id'];
                }
                $linkData = $this->model->getDataByWhere($linkWhere, 'id, video_id, video_detail_id, advertiser_id, responsibility_person_id,link_type');
                if (empty($linkData)) {
                    return [
                        'create_time' => date('Y-m-d H:i:s', $timeStamp),
                        'total_click_num' => $totalClickNum,
                        'total_new_user' => 0,
                        // 'total_order_count'=>0,
                        'data' => $data
                    ];
                } else { // by huangxiaoshan update 2023-07-13
                    return [
                        'create_time' => date('Y-m-d H:i:s', $timeStamp),
                        'total_click_num' => 0,
                        'total_new_user' => 0,
                        // 'total_order_count'=>0,
                        'data' => []
                    ];
                }
            }
        }

        $linkData = $this->model->getDataByWhere($linkWhere, 'id, video_id, video_detail_id, advertiser_id, responsibility_person_id, version, project_id, rebate, echo_rate,link_type');

        $accessToken = Common::getBaiduAccessToken();

        // $hearder['headers'] = ['Access-Token:' . $accessToken];
        $hearder['json'] = 1;

        $startDate = date('Y-m-d');
        $endDate = date('Y-m-d');
        $data = $accountIds = $responsibilityPersonIds = [];
        $url = 'https://api.baidu.com/json/feed/v1/ReportFeedService/getRealTimeFeedData';
        $subUserListKey = config('baidu.baidu_sub_user_list');
        $subUserList = $redis->hGetAll($subUserListKey);

        // 获取成本
        foreach ($linkData as $value) {
            if (empty($value['advertiser_id']) || empty($subUserList[$value['advertiser_id']])) {
                continue;
            }

            // 获取成本
            $requestData = [
                'header' => [
                    'userName' => $subUserList[$value['advertiser_id']],
                    'accessToken' => $accessToken
                ],
                'body' => [
                    'realTimeRequestType' => [
                        'performanceData' => ['cost'],
                        'startDate' => $startDate,
                        'endDate' => $endDate,
                        'levelOfDetails' => 2,
                        'reportType' => 700,
                        'unitOfTime' => 5
                    ]
                ]
            ];

            $result = Common::_curl($url, $requestData, 'POST', $hearder);
            $result = json_decode($result, true);

            if ($result['header']['desc'] == 'success' && $result['header']['status'] == 0) {
                $value['cost'] = 0;
                if (!empty($result['body']['data'])) {
                    $value['cost'] = round($result['body']['data'][0]['kpis'][0], 2);
                }

                $data[] = $value;
            } else {
                return ['message' => $result['header']['desc'] . '；link_id：' . $value['id']];
            }

            $accountIds[] = trim($value['advertiser_id']);
            $responsibilityPersonIds[] = $value['responsibility_person_id'];
        }

        $redisUserLinkRegisterData = [];
        if ($data) {
            // 短剧
            $videoIds = array_column($data, 'video_id');
            $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
            $videos = array_column($videoData, 'name', 'id');

            $ids = array_column($data, 'id');
            $userWhere = [
                ['link_id', 'in', $ids],
                ['activation_time', 'between', [date('Y-m-d') . ' 00:00:00', date('Y-m-d') . ' 23:59:59']]
            ];
            $userInfo = $this->userModel->getBatchDataByWhere($userWhere, 'id, link_id');
            $payData = $this->payRecordModel->getInfo(['link_id' => $ids, 'status' => 1, 'consume_date' => date('Ymd')], 'link_id, uid, total_fee, activation_time');

            $newUids = $newUserPayData = $rechargeNumber = $payResult = $userData = [];

            if ($userInfo) {

                foreach ($userInfo as $key => $value) {
                    $newUids[] = $value['id'];
                    $redisUserLinkRegisterData[$value['link_id']][] = $value['id'];
                }

                // 当天这个链接上的用户数据
                $links = array_column($userInfo, 'link_id');
                $linkUser = array_count_values($links); // 统计相同link_id 的个数
            }

            $newUserNum = $tencentPayData = [];
            // 当天新用户充值（当期充值）
            $startTime = strtotime(date('Y-m-d'));
            $endTime = strtotime(date('Y-m-d')) + 86400;
            foreach ($payData as $key => $value) {
                if (strtotime($value['activation_time']) >= $startTime && $endTime > strtotime($value['activation_time'])) {
                    $newUserPayData[$value['link_id']][] = $value['total_fee'];
                    $newUserNum[$value['link_id']][] = $value['uid'];
                    if ($value['pay_merchant'] == 15) {
                        $tencentPayData[$value['link_id']][] = $value['total_fee'];
                    }
                }
                // $payResult[$value['link_id']][] = $value['total_fee'];
                $rechargeNumber[$value['link_id']][] = $value['uid'];
            }

            // 获取返点数据
            $launchAccountData = $this->launchAccountModel->getDataByWhere(['account_id' => $accountIds], 'account_id, rebate');
            $launchAccount = array_column($launchAccountData, 'rebate', 'account_id');

            // 获取负责人数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'id, name');
            $responsibilityPerson = array_column($responsibilityPersonData, 'name', 'id');

            foreach ($data as $key => $item) {
                $data[$key]['video_name'] = $videos[$item['video_id']];

                $currentRecharge = empty($newUserPayData[$item['id']]) ? 0 : array_sum($newUserPayData[$item['id']]);
                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值

                // by update huangxiaoshan 2023-07-13
                $virtualPayment = empty($tencentPayData[$item['id']]) ? 0 : array_sum($tencentPayData[$item['id']]);
                $currentRechargeDiscount = round($currentRecharge * 0.9, 2); // 当期95充值;
                $data[$key]['current_recharge_discount'] = $currentRechargeDiscount;
                // end .

                $data[$key]['current_recovery'] = $item['cost'] == 0 ? 0 : round($currentRecharge / $item['cost'] * 100, 2) . '%'; // 当期回收
                $conversionNumber = empty($rechargeNumber[$item['id']]) ? 0 : count(array_unique($rechargeNumber[$item['id']])); // 充值人数
                $data[$key]['conversion_number'] = $conversionNumber;

                $newRechargeNumber = empty($newUserPayData[$item['id']]) ? 0 : count($newUserPayData[$item['id']]); // 新充笔数
                $newUserNumber = empty($newUserNum[$item['id']]) ? 0 : count(array_unique($newUserNum[$item['id']])); // 新充人数
                $data[$key]['new_recharge_number'] = $newRechargeNumber;
                $data[$key]['new_user_number'] = $newUserNumber;
                $data[$key]['conversion_cost'] = $newUserNumber == 0 ? 0 : round($item['cost'] / $newUserNumber, 2); // 转化成本

                $data[$key]['fans_cost'] = !empty($linkUser[$item['id']]) ? round($item['cost'] / $linkUser[$item['id']], 2) : 0; // 粉丝成本
                // $totalRecharge = empty($payResult[$item['id']]) ? 0 : array_sum($payResult[$item['id']]); // 当天累计充值
                $data[$key]['total_recharge'] = $currentRecharge;

                $data[$key]['per_capita_contribution'] = $newUserNumber == 0 ? 0 : round($currentRecharge / $newUserNumber, 2); // 人均贡献

                $userLinkRegisterNum = empty($redisUserLinkRegisterData[$item['id']]) ? 0 : count($redisUserLinkRegisterData[$item['id']]);
                // 转化率
                $redisKey = config('redis_key.link_same_day_click_num') . date('Ymd') . '-' . $item['id'];
                $redis->set($redisKey, $userLinkRegisterNum, 15 * 60);
                if (empty($newUserNumber) || empty($userLinkRegisterNum)) {
                    $data[$key]['conversion_rate'] = '0%';
                } else {
                    $data[$key]['conversion_rate'] = round($newUserNumber / $userLinkRegisterNum * 100, 2) . '%';
                }

                $redis->set($key2 . $item['id'], $userLinkRegisterNum, 15 * 60);
                $data[$key]['media_id'] = 3; // 百度

                // 实际花费
                $actualCost = 0;
                if (!empty($item['rebate'])) {
                    $actualCost = round($item['cost'] / ($item['rebate'] / 100 + 1), 2);
                } elseif (!empty($launchAccount[$item['advertiser_id']])) {
                    $actualCost = round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2);
                }
                unset($data[$key]['rebate']);
                // $actualCost = !empty($launchAccount[$item['advertiser_id']]) ? round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2) : 0;
                $data[$key]['actual_recovery'] = $actualCost == 0 ? 0 : round($currentRecharge / $actualCost * 100, 2) . '%'; // 实际回收
                $data[$key]['actual_cost'] = round($actualCost, 2);

                // by huangxiaoshan 2023-07-13 当期充值95折扣后净利润.
                $data[$key]['current_recharge_profit'] = round($currentRechargeDiscount - $actualCost, 2);
                // end

                // 负责人数据
                $data[$key]['responsibility_person_name'] = $responsibilityPerson[$item['responsibility_person_id']];

                $data[$key]['revenue'] = round($currentRecharge - $actualCost, 2); // 营收情况
            }
        }

        Db::name('real_time_data_cache')->where(['media_id' => 3])->delete(true);
        $bool = Db::name('real_time_data_cache')->insertAll($data);
        if ($bool) {
            $redis->set($key1, time(), 15 * 60); // 数据产生的时间
        }

        $data = Db::name('real_time_data_cache')->where($where)->order('id', 'desc')->select()->toArray();
        foreach ($data as $item) {

            // 获取点击数
            $redisKey = config('redis_key.link_same_day_click_num') . date('Ymd') . '-' . $item['id'];
            $clickNum = $redis->get($redisKey);
            $totalClickNum = $totalClickNum + $clickNum;

            // 获取当日累计注册用户数
            $linkRegisterUserNum = $redis->get($key2 . $item['id']);
            $totalNewUserCount = $totalNewUserCount + $linkRegisterUserNum;
        }

        $result = [
            'create_time' => date('Y-m-d H:i:s'),
            'total_click_num' => $totalClickNum,
            'total_new_user' => $totalNewUserCount,
            'data' => $data
        ];

        return $result;
    }

    // 腾讯今日实时在投数据
    public function getTencentInvestingData($params, $userInfo)
    {
    	$data=[];
        $where[] = ['media_id', '=', 4];
        $where[] = ['link_switch', '=', 1];
        $where[] = ['advertiser_id', '<>', ''];
        $totalClickNum = $totalNewUserCount = 0;

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        } elseif ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $where[] = ['responsibility_person_id', '=', $userInfo['cps_user_id']];
        }
        // 链接id搜索
        if (!empty($params['link_id'])) {
            $where[] = ['id', '=', $params['link_id']];
        }
        // 账户id搜索
        if (!empty($params['advertiser_id'])) {
            $where[] = ['advertiser_id', '=', $params['advertiser_id']];
        }
        // 短剧id搜索
        if (!empty($params['video_id'])) {
            $where[] = ['video_id', '=', $params['video_id']];
        }
      // 负责人搜索
      if (!empty($params['responsibility_person_id'])) {
        $where[] = ['responsibility_person_id', '=', $params['responsibility_person_id']];
        }
        // 分销商链接不查询
        $distributorResponsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['is_distributor' => 1], 'id');
        $distributorResponsibilityPersonPids = array_column($distributorResponsibilityPerson, 'id');

        $distributorPitcher = $this->responsibilityPersonModel->getDataByWhere(['pid' => $distributorResponsibilityPersonPids], 'id, pid');
        $distributorResponsibilityPersonIds = array_column($distributorPitcher, 'id');

        $where[] = ['responsibility_person_id', 'not in', $distributorResponsibilityPersonIds];
        $linkData = $this->model->getDataByWhere($where, 'id, video_id, video_detail_id, advertiser_id, responsibility_person_id, version, project_id, rebate, echo_rate, subject_id, created_at');

        // 获取redis花费数据
        $developerInfo = config('tencent.developer_info');
        $token = Common::getTencentAdDeveloperAppAccessToken($developerInfo);
        $url = 'https://api.e.qq.com/v1.3/realtime_cost/get';
        $getBalanceUrl = 'https://api.e.qq.com/v1.3/funds/get';
        $date = date('Y-m-d');
        // 获取成本
        foreach ($linkData as $value) {
            if (empty($value['advertiser_id'])) {
                continue;
            }
            $commonParameters = [
                'access_token' => $token,
                'timestamp' => time(),
                'nonce' => md5(uniqid('', true))
            ];

            $parameters = [
                'account_id' => $value['advertiser_id'],
                'level' => 'ADVERTISER',
                'date' => $date,
                'page' => 1,
                'page_size' => 10
            ];

            $parameters = array_merge($commonParameters, $parameters);

            foreach ($parameters as $key => $item) {
                if (!is_string($item)) {
                    $parameters[$key] = json_encode($item);
                }
            }

            $requestUrl = $url . '?' . http_build_query($parameters);

            $response = Common::curlRequest($requestUrl);
            $costData = json_decode($response, true);
            // dump($costData);die;
            // 花费
            $value['cost'] = 0;
            if (!empty($costData['data']['list'][0])) {
                $value['cost'] = round($costData['data']['list'][0]['cost'] / 100, 2);
            }

            // 获取余额
            // dump($value['advertiser_id']);
            $commonParameters['nonce'] = md5(uniqid('', true));
            $balanceParams = [
                'account_id' => $value['advertiser_id']
            ];
            $balanceParams = array_merge($commonParameters, $balanceParams);

            foreach ($balanceParams as $k => $val) {
                if (!is_string($val)) {
                    $balanceParams[$k] = json_encode($val);
                }
            }

            $requestBalanceUrl = $getBalanceUrl . '?' . http_build_query($balanceParams);

            $response = Common::curlRequest($requestBalanceUrl);
            $balanceData = json_decode($response, true);

            $value['balance'] = 0;
            try {
                foreach ($balanceData['data']['list'] as $balanceVal) {
                    $value['balance'] += $balanceVal['balance'];
                }
            } catch (\Exception $e) {
                return ['message' => $balanceData['message_cn'].'链接ID：'.$value['id']];
            }
            $value['balance'] = round($value['balance'] / 100, 2);

            $data[] = $value;
            $responsibilityPersonIds[] = $value['responsibility_person_id'];

            // 获取后台打开投放开关的投放账户
            // unset($redisCostData[$value['advertiser_id']]);
        }

        $redisUserLinkRegisterData = [];
        if ($data) {
            // 短剧
            $videoIds = array_column($data, 'video_id');
            $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
            $videos = array_column($videoData, 'name', 'id');

            $ids = array_column($data, 'id');
            $userWhere = [
                ['link_id', 'in', $ids],
                ['activation_time', 'between', [date('Y-m-d') . ' 00:00:00', date('Y-m-d') . ' 23:59:59']]
            ];
            $userInfo = $this->userModel->getBatchDataByWhere($userWhere, 'id, link_id');
            $payData = $this->payRecordModel->getInfo(['link_id' => $ids, 'status' => 1, 'consume_date' => date('Ymd')], 'link_id, uid, total_fee, activation_time, pay_merchant');

            $newUids = $newUserPayData = $rechargeNumber = $payResult = $userData = [];

            if ($userInfo) {

                foreach ($userInfo as $key => $value) {
                    $newUids[] = $value['id'];
                    $totalNewUserCount = count($newUids);
                    $redisUserLinkRegisterData[$value['link_id']][] = $value['id'];
                }

                // 当天这个链接上的用户数据
                $links = array_column($userInfo, 'link_id');
                $linkUser = array_count_values($links); // 统计相同link_id 的个数
            }

            $newUserNum = $tencentPayData = [];

            // 当天新用户充值（当期充值）
            $startTime = strtotime(date('Y-m-d'));
            $endTime = strtotime(date('Y-m-d')) + 86400;
            foreach ($payData as $key => $value) {
                if (strtotime($value['activation_time']) >= $startTime && $endTime > strtotime($value['activation_time'])) {
                    $newUserPayData[$value['link_id']][] = $value['total_fee'];
                    $newUserNum[$value['link_id']][] = $value['uid'];
                    if ($value['pay_merchant'] == 15) {
                        $tencentPayData[$value['link_id']][] = $value['total_fee'];
                    }
                }
                // $payResult[$value['link_id']][] = $value['total_fee'];
                $rechargeNumber[$value['link_id']][] = $value['uid'];
            }

            // 获取负责人数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'id, name');
            $responsibilityPerson = array_column($responsibilityPersonData, 'name', 'id');

            foreach ($data as $key => $item) {
                $data[$key]['video_name'] = $videos[$item['video_id']];

                $currentRecharge = empty($newUserPayData[$item['id']]) ? 0 : array_sum($newUserPayData[$item['id']]);
                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值

                // by huangxiaoshan 2023-07-13 当期充值95折扣
                $tencentTenPercent = empty($tencentPayData[$item['id']]) ? 0 : array_sum($tencentPayData[$item['id']]);
                $currentRechargeDiscount = round($currentRecharge * 0.9, 2); // 当期95充值;

                $data[$key]['current_recharge_discount'] = $currentRechargeDiscount;
                // end.

                $data[$key]['current_recovery'] = $item['cost'] == 0 ? 0 : round($currentRechargeDiscount / $item['cost'] * 100, 2) . '%'; // 当期回收
                $conversionNumber = empty($rechargeNumber[$item['id']]) ? 0 : count(array_unique($rechargeNumber[$item['id']])); // 充值人数
                $data[$key]['conversion_number'] = $conversionNumber;

                $newRechargeNumber = empty($newUserPayData[$item['id']]) ? 0 : count($newUserPayData[$item['id']]); // 新充笔数
                $newUserNumber = empty($newUserNum[$item['id']]) ? 0 : count(array_unique($newUserNum[$item['id']])); // 新充人数
                $data[$key]['new_recharge_number'] = $newRechargeNumber;
                $data[$key]['new_user_number'] = $newUserNumber;
                // $data[$key]['conversion_cost'] = $newUserNumber == 0 ? 0 : round($item['cost'] / $newUserNumber, 2); // 转化成本

                // 转化率
                $data[$key]['conversion_rate'] = !empty($linkUser[$item['id']]) ? round($newUserNumber / $linkUser[$item['id']] * 100, 2) . '%' : '0%';
                $totalClickNum += empty($linkUser[$item['id']]) ? 0 : $linkUser[$item['id']];

                // $data[$key]['fans_cost'] = !empty($linkUser[$item['id']]) ? round($item['cost'] / $linkUser[$item['id']], 2) : 0; // 粉丝成本
                // $totalRecharge = empty($payResult[$item['id']]) ? 0 : array_sum($payResult[$item['id']]); // 当天累计充值
                $data[$key]['total_recharge'] = $currentRecharge;

                $data[$key]['per_capita_contribution'] = $newUserNumber == 0 ? 0 : round($currentRecharge / $newUserNumber, 2); // 人均贡献

                $userLinkRegisterNum = empty($redisUserLinkRegisterData[$item['id']]) ? 0 : count($redisUserLinkRegisterData[$item['id']]);
                // $redis->set($key2.$item['id'], $userLinkRegisterNum, 15*60);
                $data[$key]['media_id'] = 1; // 抖音

                // 实际花费
                $actualCost = round($item['cost'] / ($item['rebate'] / 100 + 1), 2);

                unset($data[$key]['rebate']);

                $data[$key]['conversion_cost'] = $newUserNumber == 0 ? 0 : round($actualCost / $newUserNumber, 2); // 转化成本
                $data[$key]['fans_cost'] = !empty($userData[$item['id']]) ? round($actualCost / $userData[$item['id']], 2) : 0; // 粉丝成本

                // $actualCost = !empty($launchAccount[$item['advertiser_id']]) ? round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2) : 0;
                $data[$key]['actual_recovery'] = $actualCost == 0 ? 0 : round($currentRechargeDiscount / $actualCost * 100, 2) . '%'; // 实际回收
                $data[$key]['actual_cost'] = round($actualCost, 2);

                // by huangxiaoshan 2023-07-13 当期充值95折扣后净利润.
                $data[$key]['current_recharge_profit'] = round($currentRechargeDiscount - $actualCost, 2);
                // end

                // 负责人数据
                $data[$key]['responsibility_person_name'] = $responsibilityPerson[$item['responsibility_person_id']];

                $data[$key]['revenue'] = round($currentRecharge - $actualCost, 2); // 营收情况
                // by huangxiaoshan 2023-07-24 人均订单数.
                $data[$key]['avg_person_order'] = 0;
                if($newRechargeNumber && $newUserNumber) {
                    $data[$key]['avg_person_order'] = round(bcdiv((string)$newRechargeNumber, (string)$newUserNumber, 3), 2);
                }
                // end
                unset($data[$key]['subject_id']);
            }
        }

        $result = [
            'create_time' => date('Y-m-d H:i:s'),
            'total_click_num' => $totalClickNum,
            'total_new_user' => $totalNewUserCount,
            'data' => $data,
        ];

        return $result;
    }

    // 按短剧统计
    public function getByShortPlayList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];
        if (!empty($params['video_id'])) {
            $where['id'] = $params['video_id'];
        }

        if (!empty($params['original_id'])) {
            $where['original_id'] = $params['original_id'];
        }

        $data = $this->videosModel->getPagingDataByWhere($where, $page, $limit, 'id, name, original_id');

        if ($data['data']) {
            $videoIds = array_column($data['data'], 'id');

            $linkData = $this->model->getDataByWhere(['video_id' => $videoIds], 'id, video_id, responsibility_person_id');
            $link = [];
            foreach ($linkData as $key => $value) {
                $link[$value['video_id']][] = $value['id'];
            }

            $linkIds = array_column($linkData, 'id');

            $dailyDeliveryData = $this->dailyDeliveryDataModel->getDataByWhere(['link_id' => $linkIds], 'link_id, cost, actual_cost, register_user_num, activation_user_num, current_recharge, total_recharge, recharge_number, conversion_number, date,new_user_number');

            $dailyDeliveryDataResult = [];
            foreach ($dailyDeliveryData as $key => $value) {
                foreach ($link as $videoId => $item) {
                    if (in_array($value['link_id'], $item)) {
                        $dailyDeliveryDataResult[$videoId][] = $value;
                    }
                }
            }

            foreach ($data['data'] as $key => $value) {

                $cost =$newUserNumber = $actualCost = $registerUserNum = $activationUserNum = $currentRecharge = $totalRecharge = $rechargeNumber = $conversionNumber = $perCapitaContribution = $revenue = $tmpRechargeDiscount = $totalIncome = 0;
                $currentRecovery = $totalRecovery = '0%';

                if (!empty($dailyDeliveryDataResult[$value['id']])) {

                    foreach ($dailyDeliveryDataResult[$value['id']] as $k => $item) {
                        $cost = $cost + $item['cost'];
                        $actualCost = $actualCost + $item['actual_cost'];
                        $registerUserNum = $registerUserNum + $item['register_user_num'];
                        $activationUserNum = $activationUserNum + $item['activation_user_num'];
                        if ($item['date'] >= 20230821) {
                            $tmpRechargeDiscount = $tmpRechargeDiscount + $item['current_recharge'] * 0.9;
                            $totalIncome = $totalIncome + $item['total_recharge'] * 0.9;
                        } else {
                            $tmpRechargeDiscount = $tmpRechargeDiscount + $item['current_recharge'] * 0.95;
                            $totalIncome = $totalIncome + $item['total_recharge'] * 0.95;
                        }
                        $totalRecharge = $totalRecharge + $item['total_recharge'];
                        $currentRecharge = $currentRecharge + $item['current_recharge'];
                        $rechargeNumber = $rechargeNumber + $item['recharge_number']; // 订单数
                        $conversionNumber = $conversionNumber + $item['conversion_number'];
                        $newUserNumber    = $newUserNumber + $item['new_user_number'];
                    }

                    $currentRecovery = intval($cost) == 0 ? '0%' : round($tmpRechargeDiscount / $actualCost * 100, 2).'%';
                    $totalRecovery = intval($cost) == 0 ? '0%' : round($totalIncome / $actualCost * 100, 2).'%';
                }

                $data['data'][$key]['cost'] = round($cost, 2); // 花费
                $data['data'][$key]['actual_cost'] = round($actualCost, 2); // 实际花费
                $data['data'][$key]['register_user_num'] = $registerUserNum; // 注册人数
                $data['data'][$key]['activation_user_num'] = $activationUserNum; // 激活人数
                $data['data'][$key]['current_recharge'] = sprintf('%.2f', $currentRecharge); // 当期充值

                $data['data'][$key]['current_recharge_discount'] = round($tmpRechargeDiscount, 2);
                $data['data'][$key]['current_recharge_profit'] = round($totalIncome - $actualCost, 2);
                // end

                $data['data'][$key]['current_recovery'] = $currentRecovery; // 当期回收
                $data['data'][$key]['total_recharge'] = round($totalRecharge, 2); // 累计充值
                $data['data'][$key]['total_income'] = round($totalIncome, 2);
                $data['data'][$key]['total_recovery'] = $totalRecovery; // 累计回收
                $data['data'][$key]['recharge_number'] = $rechargeNumber; // 订单数
                $data['data'][$key]['conversion_number'] = $conversionNumber; // 充值人数
                $data['data'][$key]['conversion_cost'] = $newUserNumber ? round($actualCost / $newUserNumber, 2) : 0; // 转化成本

                $data['data'][$key]['revenue'] = round($totalRecharge - $actualCost, 2); // 营收情况
                $data['data'][$key]['per_capita_contribution'] = $conversionNumber == 0 ? 0 : round($currentRecharge / $newUserNumber, 2); // 充值用户贡献
            }
        }
        return $data;
    }

    // 按短剧统计合计
    public function getByShortPlayCount($params)
    {
        $where = [];
        if (!empty($params['video_id'])) {
            $where['id'] = $params['video_id'];
        }

        if (!empty($params['original_id'])) {
            $where['original_id'] = $params['original_id'];
        }

        if (empty($where)) {
            $data = Db::name('daily_delivery_data')->field('sum(cost) as cost, sum(actual_cost) as actual_cost, sum(register_user_num) as register_user_num, sum(activation_user_num) as activation_user_num, sum(current_recharge) as current_recharge, sum(total_recharge) as total_recharge, sum(conversion_number) as conversion_number, sum(new_recharge_number) as new_recharge_number, sum(recharge_number) as recharge_number, sum(new_user_number) as new_user_number, sum(revenue) as revenue, sum(case when date <= 20230821 then current_recharge * 0.95 else current_recharge * 0.9 end) as current_recharge_discount, sum(case when date <= 20230821 then total_recharge * 0.95 else total_recharge * 0.9 end) as total_income')->select()->toArray();
            $data = $data[0];
        } else {
            $videoData = $this->videosModel->getInfoByWhere($where, 'id');

            $linkData = $this->model->getDataByWhere(['video_id' => $videoData['id']], 'id');
            $linkIds = array_column($linkData, 'id');

            $data = Db::name('daily_delivery_data')->field('sum(cost) as cost, sum(actual_cost) as actual_cost, sum(register_user_num) as register_user_num, sum(activation_user_num) as activation_user_num, sum(current_recharge) as current_recharge, sum(total_recharge) as total_recharge, sum(conversion_number) as conversion_number, sum(new_recharge_number) as new_recharge_number, sum(recharge_number) as recharge_number, sum(new_user_number) as new_user_number, sum(revenue) as revenue, sum(case when date <= 20230821 then current_recharge * 0.95 else current_recharge * 0.9 end) as current_recharge_discount, sum(case when date <= 20230821 then total_recharge * 0.95 else total_recharge * 0.9 end) as total_income')->where(['link_id' => $linkIds])->find();

        }

        $data['current_recharge_profit'] = round($data['total_income'] - $data['actual_cost'], 2);
        $data['current_recovery'] = round($data['current_recharge_discount'] / $data['actual_cost'] * 100, 2) . '%';
        $data['total_recovery'] = round($data['total_income'] / $data['actual_cost'] * 100, 2) . '%';
        $data['conversion_cost'] = round($data['actual_cost'] / $data['conversion_number'], 2);
        $data['per_capita_contribution'] = round($data['total_recharge'] / $data['conversion_number'], 2);

        $data['current_recharge_discount'] = round($data['current_recharge_discount'], 2);
        $data['total_recharge'] = round($data['total_recharge'], 2);
        $data['current_recharge'] = sprintf('%.2f', $data['current_recharge']);

        $data['total_income'] = round($data['total_income'], 2);
        return $data;
    }

    /**
     * 订单总数，就是推广链接的实时费用花费列表里面的快手，百度，抖音。
     * @param array $data
     * @return int|mixed
     */
    private function linkOrderCount($data = [])
    {
        if ($data) {
            $total_order_count = 0;
            foreach ($data as $key => $val) {
                $total_order_count += (isset($val['order_count']) && $val['order_count']) ? $val['order_count'] : 0;
            }
            return $total_order_count;
        }
        return 0;
    }

    // 按负责人统计列表
    public function getByPeopleList($params, $userInfo)
    {
        if ($userInfo['cps_user_id'] != 13 && $userInfo['is_branch_office_manage'] != 1) {
            return ['message' => Error::NOT_REQUEST_AUTH_MESSAGE];
        }

        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $where = [];
        if ($userInfo['is_branch_office_manage'] == 1) {
            // 分公司负责人
            $where[] = [
                'pid', '=', $userInfo['cps_user_id']
            ];
        } else {
            $branchOfficeManage = $this->responsibilityPersonModel->getDataByWhere(['is_branch_office_manage' => 1], 'id');
            $manageIds = array_column($branchOfficeManage, 'id');
            // cps总帐号
            $where[] = ['id', 'not in', config('link.not_query')];
            $where[] = ['pid', 'in', $manageIds];
        }

        // 投手搜索
        if (!empty($params['responsibility_person_id'])) {
            $where[] = ['id', '=', $params['responsibility_person_id']];
        }
        // 公司搜索
        if (!empty($params['company_id'])) {
            $where[] = ['company_id', '=', $params['company_id']];
        }

        $data = $this->responsibilityPersonModel->getDataByWhere($where, 'id, name');

        if ($data) {
            $responsibilityPersonIds = array_column($data, 'id');
            $linkData = $this->model->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id, responsibility_person_id');

            $link = [];
            foreach ($linkData as $key => $value) {
                $link[$value['responsibility_person_id']][] = $value['id'];
            }
            $linkIds = array_column($linkData, 'id');
            $where = [];
            $where[] = ['link_id', 'in', $linkIds];
            if (!empty($params['start_date'])) {
                $startDate = str_replace('-', '', $params['start_date']);
                $where[] = ['date', '>=', $startDate];
            }
            if (!empty($params['end_date'])) {
                $endDate = str_replace('-', '', $params['end_date']);
                $where[] = ['date', '<=', $endDate];
            }

            $dailyDeliveryData = $this->dailyDeliveryDataModel->getDataByWhere($where, 'date, link_id, cost, actual_cost, register_user_num, activation_user_num, current_recharge, total_recharge, recharge_number, conversion_number, virtual_payment');

            $dailyDeliveryDataResult = [];
            foreach ($dailyDeliveryData as $key => $value) {
                foreach ($link as $k => $item) {
                    if (in_array($value['link_id'], $item)) {
                        $dailyDeliveryDataResult[$k][] = $value;
                    }
                }
            }

            foreach ($data as $key => $value) {

                $cost = $actualCost = $registerUserNum = $activationUserNum = $currentRecharge = $totalRecharge = $rechargeNumber = $conversionNumber = $perCapitaContribution = $revenue = 0;
                $currentRecovery = $totalRecovery = '0%';
                $virtualPayment = $currentRechargeDiscount = $totalIncome = 0;

                if (!empty($dailyDeliveryDataResult[$value['id']])) {

                    foreach ($dailyDeliveryDataResult[$value['id']] as $k => $item) {
                        $cost = $cost + $item['cost'];
                        $actualCost = $actualCost + $item['actual_cost'];
                        $registerUserNum = $registerUserNum + $item['register_user_num'];
                        $activationUserNum = $activationUserNum + $item['activation_user_num'];
                        if ($item['date'] < 20230821) {
                            $currentRechargeDiscount = $currentRechargeDiscount + $item['current_recharge'] * 0.95;
                            $totalIncome = $totalIncome + $item['total_recharge'] * 0.95;
                        } else {
                            $currentRechargeDiscount = $currentRechargeDiscount + $item['current_recharge'] * 0.9;
                            $totalIncome = $totalIncome + $item['total_recharge'] * 0.9;
                        }
                        $totalRecharge = $totalRecharge + $item['total_recharge'];
                        $currentRecharge = $currentRecharge + $item['current_recharge'];
                        $rechargeNumber = $rechargeNumber + $item['recharge_number']; // 订单数
                        $conversionNumber = $conversionNumber + $item['conversion_number'];
                        $virtualPayment = $virtualPayment + $item['virtual_payment'];
                    }

                    $currentRecovery = intval($actualCost) == 0 ? '0%' : round($currentRechargeDiscount / $actualCost * 100, 2) . '%';
                    $totalRecovery = intval($actualCost) == 0 ? '0%' : round($totalIncome / $actualCost * 100, 2) . '%';
                }

                $data[$key]['cost'] = round($cost, 2); // 花费
                $data[$key]['actual_cost'] = round($actualCost, 2); // 实际花费
                $data[$key]['register_user_num'] = $registerUserNum; // 注册人数
                $data[$key]['activation_user_num'] = $activationUserNum; // 激活人数
                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值
                // by update huangxiaoshan 2023-07-13
                $data[$key]['current_recharge_discount'] = round($currentRechargeDiscount, 2);
                $data[$key]['current_recharge_profit'] = round($totalIncome - $actualCost, 2);
                // end
                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值
                $data[$key]['current_recovery'] = $currentRecovery; // 当期回收
                $data[$key]['total_recharge'] = round($totalRecharge, 2); // 累计充值
                $data[$key]['total_income'] = round($totalIncome, 2);
                $data[$key]['total_recovery'] = $totalRecovery; // 累计回收
                $data[$key]['recharge_number'] = $rechargeNumber; // 订单数
                $data[$key]['conversion_number'] = $conversionNumber; // 充值人数

                $data[$key]['revenue'] = round($totalIncome - $actualCost, 2); // 营收情况
                $data[$key]['per_capita_contribution'] = $conversionNumber == 0 ? 0 : round($totalRecharge / $conversionNumber, 2); // 充值用户贡献
            }
        } else {
            $data = [];
        }
        return $data;
    }

    // 获取每个负责人统计详细
    public function getPeopleDetail($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $responsibilityPersonId = $params['id'];
        $where = ['responsibility_person_id' => $responsibilityPersonId];

        if (!empty($params['media_id'])) {
            $where['media_id'] = $params['media_id'];
        }

        $responsibilityPerson = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'name');
        $linkData = $this->model->getDataByWhere($where, 'id, responsibility_person_id');

        $linkIds = array_column($linkData, 'id');

        $total = Db::name('daily_delivery_data')->where(['link_id' => $linkIds])->group('month')->count();

        if ($total == 0) {
            return ['total' => 0, 'total_page' => 0, 'data' => []];
        }
        $totalPage = ceil($total / $limit);
        $offset = ($page - 1) * $limit;

        $data = Db::name('daily_delivery_data')->field('month')->where(['link_id' => $linkIds])->group('month')->order('month desc')->limit($offset, $limit)->select()->toArray();

        $month = array_column($data, 'month');
        $dailyDeliveryData = $this->dailyDeliveryDataModel->getDataByWhere(['link_id' => $linkIds, 'month' => $month], 'month, link_id, cost, actual_cost, register_user_num, activation_user_num, current_recharge, total_recharge, recharge_number, conversion_number, new_recharge_number, new_user_number, conversion_cost, conversion_rate, current_recovery, date');

        $dailyDeliveryDataResult = [];
        foreach ($dailyDeliveryData as $key => $value) {
            $dailyDeliveryDataResult[$value['month']][] = $value;
        }

        foreach ($data as $key => $value) {
            $data[$key]['month'] = substr($value['month'], 0, 4) . '-' . substr($value['month'], 4, 2);
            $cost = $actualCost = $registerUserNum = $activationUserNum = $currentRecharge = $totalRecharge = $rechargeNumber = $conversionNumber = $perCapitaContribution = $revenue = $currentIncome = $totalIncome = 0;
            $currentRecovery = $totalRecovery = '0%';

            if (!empty($dailyDeliveryDataResult[$value['month']])) {

                foreach ($dailyDeliveryDataResult[$value['month']] as $item) {
                    $cost = $cost + $item['cost'];
                    $actualCost = $actualCost + $item['actual_cost'];
                    $registerUserNum = $registerUserNum + $item['register_user_num'];
                    $activationUserNum = $activationUserNum + $item['activation_user_num'];
                    $currentRecharge = $currentRecharge + $item['current_recharge'];
                    $totalRecharge = $totalRecharge + $item['total_recharge'];
                    $rechargeNumber = $rechargeNumber + $item['recharge_number']; // 订单数
                    $conversionNumber = $conversionNumber + $item['conversion_number'];

                    if ($item['date'] >= 20230821) {
                        $currentIncome = $currentIncome + $item['current_recharge'] * 0.9;
                        $totalIncome = $totalIncome + $item['total_recharge'] * 0.9;
                    } else {
                        $currentIncome = $currentIncome + $item['current_recharge'] * 0.95;
                        $totalIncome = $totalIncome + $item['total_recharge'] * 0.95;
                    }
                }

                $currentRecovery = intval($actualCost) == 0 ? '0%' : round($currentIncome / $actualCost * 100, 2) . '%';
                $totalRecovery = intval($actualCost) == 0 ? '0%' : round($totalIncome / $actualCost * 100, 2) . '%';
            }

            $data[$key]['cost'] = round($cost, 2); // 花费
            $data[$key]['actual_cost'] = round($actualCost, 2); // 实际花费
            $data[$key]['register_user_num'] = $registerUserNum; // 注册人数
            $data[$key]['activation_user_num'] = $activationUserNum; // 激活人数
            $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值
            $data[$key]['current_income'] = round($currentIncome, 2);
            $data[$key]['current_recovery'] = $currentRecovery; // 当期回收
            $data[$key]['total_recharge'] = round($totalRecharge, 2); // 累计充值
            $data[$key]['total_income'] = round($totalIncome, 2);
            $data[$key]['total_recovery'] = $totalRecovery; // 累计回收
            $data[$key]['recharge_number'] = $rechargeNumber; // 订单数
            $data[$key]['conversion_number'] = $conversionNumber; // 充值人数
            $data[$key]['responsibility_person_name'] = $responsibilityPerson['name']; // 负责人
            $data[$key]['responsibility_person_id'] = $responsibilityPersonId;
            $data[$key]['revenue'] = round($totalIncome - $actualCost, 2); // 营收情况
            $data[$key]['per_capita_contribution'] = $conversionNumber == 0 ? 0 : round($totalRecharge / $conversionNumber, 2); // 充值用户贡献
        }
        return ['total' => $total, 'total_page' => $totalPage, 'data' => $data];
    }

    // 每个负责人按月份合计
    public function getPeopleDetailCount($params)
    {
        $responsibilityPersonId = $params['id'];
        $where = ['responsibility_person_id' => $responsibilityPersonId];

        if (!empty($params['media_id'])) {
            $where['media_id'] = $params['media_id'];
        }

        $responsibilityPerson = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'name');
        $linkData = $this->model->getDataByWhere($where, 'id, responsibility_person_id');

        $linkIds = array_column($linkData, 'id');

        $data = Db::name('daily_delivery_data')->field('sum(cost) as cost, sum(actual_cost) as actual_cost, sum(register_user_num) as register_user_num, sum(activation_user_num) as activation_user_num, sum(current_recharge) as current_recharge, sum(total_recharge) as total_recharge, sum(recharge_number) as recharge_number, sum(conversion_number) as conversion_number, sum(revenue) as revenue, sum(case when date < 20230821 then current_recharge * 0.95 else current_recharge * 0.9 end) as current_income, sum(case when date < 20230821 then total_recharge * 0.95 else total_recharge * 0.9 end) as total_income')->where(['link_id' => $linkIds])->find();

        $data['revenue'] = round($data['total_income'] - $data['actual_cost'], 2);
        $data['current_recovery'] = $data['actual_cost'] > 0 ? round($data['current_income'] / $data['actual_cost'] * 100, 2) . '%' : '';
        $data['total_recovery'] = $data['actual_cost'] > 0 ? round($data['total_income'] / $data['actual_cost'] * 100, 2) . '%' : '';

        $data['total_income'] = $data['total_income'] > 0 ? round($data['total_income'], 2) : 0;
        $data['current_income'] = $data['total_income'] > 0 ? round($data['current_income'], 2) : 0;

        return $data;
    }
}
